<!-- 
  组件说明：轮播图组件。
  配置项：图片资源（必须）、容器宽度（可选，默认700）、容器高度（可选，默认1100）、轮播时间（可选，默认2000）。
  组件支持传入两个插槽（上一张（left-btn）、下一张（right-btn））。
  组件依赖：无。
 -->
<template>
    <div class="slide-content" :style="{width: width + 'px', height: height + 'px'}">
      <div class="slide-view" @mouseenter="off" @mouseleave="on">
        <div class="pic-view">
          <img v-for="(item, index) in imgData" :key="index" :src="item" v-show="currentIndex === index">
        </div>
        <div class="left" @click="changePage('left')"><slot name="left-btn"></slot></div>
        <div class="right" @click="changePage('right')"><slot name="right-btn"></slot></div>
        <div class="slide-index">
         <div v-for="(_, index) in imgData" :key="index" :class="{ selected: currentIndex === index }"></div>
        </div>
      </div>
    </div>
</template>

<script>
import { ref, onMounted } from "vue"
import { dataImg } from './assets'
export default {
  // 传入配置项
  props:{
    // 图片资源
    imgData: {
      type: Array,
      // required: true,
      default: dataImg
    },
    // 容器宽度
    width: {
      type: Number,
      default: 1100
    },
    // 容器高度
    height: {
      type: Number,
      default: 700
    },
    // 轮播时间
    delay: {
      type: Number,
      default: 2000,
      validator: value => {
        return value > 500
      }
    }
  },
  setup(props) {
    // 当前展示图片下标
    let currentIndex = ref(0)
    // 定时器控件
    let stop = null

    // 左右翻页
    const changePage = (dir) => {
      if (dir === "left") {
        currentIndex.value--
        if(currentIndex.value === -1) currentIndex.value = props.imgData.length - 1
      } else if (dir === "right") {
        currentIndex.value++
        currentIndex.value %= props.imgData.length
      } else {
        return
      }
    }

    // 开启轮播
    const on = () => {
        stop = setInterval(() => {
          changePage("right")
        }, 2000)
    }
    // 关闭轮播
    const off = () => {
      clearInterval(stop)
    }

    // dom挂载完成时开启轮播
    onMounted(() => {
      on()
    })

    return {
      currentIndex,
      on,
      off,
      changePage
    }
  }
}
</script>

<style scoped>
  .slide-content {
    background-color: #bfa;
    position: relative;
    overflow: hidden;
  }
  .left, .right{
    width: 50px;
    height: 100px;
    background-color: #999;
    opacity: .6;
    position: absolute;
    text-align: center;
    cursor: pointer;
    user-select: none;
  }
  .left {
    top: 50%;
    left: 0;
    transform: translateY(-50%);
  }
  .right {
    top: 50%;
    right: 0;
    transform: translateY(-50%);
  }
  .slide-index {
    display: flex;
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
  }
  .slide-index div{
    width: 15px;
    height: 15px;
    border-radius: 50%;
    background-color: #666;
    opacity: .5;
    margin: 0 5px;
  }
  .selected {
    background-color: red !important;
  }
</style>